package com.brds.netty.io;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * Netty 的 `EventLoop`调度实现
 *
 * @author galudisu
 */
public class NettyEventLoopScheduled {

    public static void main(String[] args) throws InterruptedException {

        SimpleDiscardHandler handler = new SimpleDiscardHandler();
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(group).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(8888))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(handler);

                    // ScheduledFuture<?> future = ch.eventLoop().schedule(new Runnable() {
                    ScheduledFuture<?> future = ch.eventLoop().scheduleAtFixedRate(new Runnable() {
                        @Override
                        public void run() {
                            System.out.println("60 seconds later");
                        }
                    }, 60, 60, TimeUnit.SECONDS); // 60秒后执行，然后每60秒执行一次



                }
            });
            ChannelFuture f = b.bind().sync();

            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }

    @ChannelHandler.Sharable
    private static class SimpleDiscardHandler extends SimpleChannelInboundHandler<Object> {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
            // No need to do anything special
        }
    }

}
